package org.jeecg.modules.rental.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.boot.starter.lock.client.RedissonLockClient;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.desensitization.util.SensitiveInfoUtil;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.rental.constant.RentalConstant;
import org.jeecg.common.rental.vo.LoginRentalAccount;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.rental.constant.RentalCacheConstant;
import org.jeecg.modules.rental.entity.RentalAccount;
import org.jeecg.modules.rental.entity.RentalAccountPackage;
import org.jeecg.modules.rental.entity.RentalEBike;
import org.jeecg.modules.rental.mapper.*;
import org.jeecg.modules.rental.service.IRentalAccountService;
import org.jeecg.modules.rental.util.RandomUtil;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

/**
 * @Description: 租车支付账号
 * @Author: sean
 * @Date:   2024-04-28
 * @Version: V1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RentalAccountServiceImpl extends ServiceImpl<RentalAccountMapper, RentalAccount> implements IRentalAccountService {

    private final CacheManager cacheManager;

    private final RentalOrderMapper rentalOrderMapper;

    private final RentalEBikeTypeMapper rentalEBikeTypeMapper;

    private final RentalEBikeMapper rentalEBikeMapper;

    private final RentalAccountPackageMapper rentalAccountPackageMapper;

//    @Autowired
//    private RentalWithdrawalReviewMapper rentalWithdrawalReviewMapper;

//    @Autowired
//    private WechatServiceFactory wechatServiceFactory;

//    @Override
//    public Map<String, Object> auth(String code) {
//        Map<String, Object> map = new HashMap<>();
//        String result = sendGet("https://api.weixin.qq.com/sns/jscode2session",
//                "appid=" + PayConstants.APP_ID + //小程序APPID
//                        "&secret="+ PayConstants.APP_SECRET + //小程序秘钥
//                        "&js_code="+ code + //前端传来的code
//                        "&grant_type=authorization_code");
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        if (jsonObject.containsKey("errcode")) {
//            throw new JeecgBootException("code无效");
//        }
//        String openId = jsonObject.get("openid").toString();
//        if (StringUtils.isEmpty(openId)) {
//            throw new JeecgBootException("openid为空");
//        }
//        map.put("openid", openId);
//        String sessionKey = jsonObject.get("session_key").toString();
//        if (StringUtils.isEmpty(sessionKey)) {
//            throw new JeecgBootException("session_key为空");
//        }
//        map.put("session_key", sessionKey);
//        return map;
//    }


//    @Override
//    public String authPhone(String encryptedData, String session_key, String iv) {
//        String result = WechatUtil.wxDecrypt(encryptedData, session_key, iv);
//        JSONObject json = JSONObject.parseObject(result);
//        if (json.containsKey("phoneNumber")) {
//            String phone = json.getString("phoneNumber");
////            String appid = json.getJSONObject("watermark").getString("appid");
//            if (StringUtils.isNoneBlank(phone)) {
//                return phone;
//            } else {
//                return null;
//            }
//        } else {
//            return null;
//        }
//    }

//    @Override
//    @Transactional
//    public void create(AddRentalAccountReq req) throws Exception {
//        if (StringUtils.isNotEmpty(req.getOpenId())){
//            RentalAccount rentalPayAccount = baseMapper.selectById(req.getOpenId());
//            if (rentalPayAccount==null){
//                //新增
//                rentalPayAccount = new RentalAccount();
//                //openId做主键
//                rentalPayAccount.setAccountId(req.getOpenId());
//                rentalPayAccount.setAccountCode(RandomUtil.getRandomCode());
//                rentalPayAccount.setAccountName(req.getAccountName());
//                rentalPayAccount.setNickName(req.getNickName());
//                rentalPayAccount.setPhone(req.getPhone());
//                rentalPayAccount.setImage(req.getImage());
//                rentalPayAccount.setAccountBalance(new BigDecimal(0.00));
//                rentalPayAccount.setIdentityName(req.getIdentityName());
//                rentalPayAccount.setIdentityNumber(req.getIdentityNumber());
//                // 处理推荐人账户编号
//                if (StringUtils.isNotEmpty(req.getAccountCode())) {
//                    RentalAccount recommendAccount = baseMapper.selectOne(new QueryWrapper<RentalAccount>().eq("account_code", req.getAccountCode()));
//                    if (recommendAccount != null) {
//                        rentalPayAccount.setRecommendBy(recommendAccount.getAccountId()); // 设置推荐人ID
//                    } else {
//                        // 可以选择抛出异常或记录日志，提示推荐人账户编号无效
//                        // throw new JeecgBootException("推荐人账户编号无效");
//                        log.warn("rentalpayaccount.service.referrer.invalid");
//                    }
//                }
//                if (StringUtils.isEmpty(req.getSysOrgCode())){
//                    throw new JeecgBootException("rentalpayaccount.service.service.org.missing");
//                }else{
//                    rentalPayAccount.setSysOrgCode(req.getSysOrgCode());
//                }
//                rentalPayAccount = resetPassword(rentalPayAccount);
//                this.save(rentalPayAccount);
//            }else if(ObjectUtil.isEmpty(rentalPayAccount.getIdentityNumber())) {
//                rentalPayAccount.setAccountName(req.getAccountName());
//                rentalPayAccount.setNickName(req.getNickName());
//                rentalPayAccount.setPhone(req.getPhone());
//                rentalPayAccount.setImage(req.getImage());
//                rentalPayAccount.setAccountBalance(new BigDecimal(0.00));
//                rentalPayAccount.setIdentityName(req.getIdentityName());
//                rentalPayAccount.setIdentityNumber(req.getIdentityNumber());
//                // 处理推荐人账户编号
//                if (StringUtils.isNotEmpty(req.getAccountCode())) {
//                    RentalAccount recommendAccount = baseMapper.selectOne(new QueryWrapper<RentalAccount>().eq("account_code", req.getAccountCode()));
//                    if (recommendAccount != null) {
//                        rentalPayAccount.setRecommendBy(recommendAccount.getAccountId()); // 设置推荐人ID
//                    } else {
//                        // 可以选择抛出异常或记录日志，提示推荐人账户编号无效
//                        // throw new JeecgBootException("推荐人账户编号无效");
//                        log.warn("rentalpayaccount.service.referrer.invalid");
//                    }
//                }
//                this.updateById(rentalPayAccount);
//            }else{
//                throw new JeecgBootException("rentalpayaccount.service.user.already.authorized");
//            }
//        }else{
//            throw new JeecgBootException("rentalpayaccount.service.auth.id.missing");
//        }
//
//    }

//    @Override
//    public Integer authentication(AddAuthenticationReq req) throws IOException {
//
//        RentalAccount rentalPayAccount = baseMapper.selectById(req.getAccountId());
//        if (rentalPayAccount==null){
//            throw new JeecgBootException("rentalpayaccount.service.auth.user.not.found");
//        }
//
//        if (rentalPayAccount.getReviewStatus()!=null&&rentalPayAccount.getReviewStatus()==2){
//            throw new JeecgBootException("rentalpayaccount.service.auth.user.already.verified");
//        }
//
//        Map<String, String> params = new HashMap<>();
//        //image 和 url 二选一 ，选择其中一个时，请注释另外一个参数,默认使用image
//        params.put("url",req.getIdentityPositive());
//        Orc orc = Sample.orc(req.getIdentityPositive());
//        //暂时跳过身份识别
//        rentalPayAccount.setIdentityName(req.getIdentityName());
//
//        rentalPayAccount.setIdentityPositive(req.getIdentityPositive());
//        //实名认证通过后修改认证状态
//        rentalPayAccount.setReviewStatus(2);
//        baseMapper.updateById(rentalPayAccount);
//
//        return 1;
//    }

//    public static String sendGet(String url, String param) {
//        String result = "";
//        BufferedReader in = null;
//        try {
//            String urlNameString = url + "?" + param;
//            URL realUrl = new URL(urlNameString);
//            // 打开和URL之间的连接
//            URLConnection connection = realUrl.openConnection();
//            // 设置通用的请求属性
//            connection.setRequestProperty("accept", "*/*");
//            connection.setRequestProperty("connection", "Keep-Alive");
//            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            // 建立实际的连接
//            connection.connect();
//            // 获取所有响应头字段
//            Map<String, List<String>> map = connection.getHeaderFields();
//            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
//            // 定义 BufferedReader输入流来读取URL的响应
//            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//            String line;
//            while ((line = in.readLine()) != null) {
//                result += line;
//            }
//        } catch (Exception e) {
//            System.out.println("发送GET请求出现异常！" + e);
//            e.printStackTrace();
//        }
//        // 使用finally块来关闭输入流
//        finally {
//            try {
//                if (in != null) {
//                    in.close();
//                }
//            } catch (Exception e2) {
//                e2.printStackTrace();
//            }
//        }
//        return result;
//    }



//    @Override
//    public Result<List<AccountRentalPackegeRsp>> accountPackge(String openId, Integer accountPackgeType) {
////        List<AccountRentalPackegeRsp> accountPackge = rentalAccountPackgeMapper.getRentalAccountPackge(openId, accountPackgeType);
////        return Result.OK(accountPackge);
//        return Result.OK();
//    }
//
//    @Override
//    public Result<List<RentalPackge>> allowCoupons(String openId) {
//        RentalAccount rentalPayAccount=baseMapper.selectById(openId);
//        if (rentalPayAccount!=null){
////            if (rentalPayAccount.getCarTypeId()!=null&&rentalPayAccount.getDepositType()==2){
////                LambdaQueryWrapper<RentalPackge> queryWrapper = new LambdaQueryWrapper<>();
////                queryWrapper.eq(RentalPackge::getCarTypeId,rentalPayAccount.getCarId());
////                List<RentalPackge> dataList = rentalPackgeMapper.selectList(queryWrapper);
////                return Result.OK(dataList);
////            }
//        }
//        throw new JeecgBootException("rentalpayaccount.service.user.not.paid.deposit");
//    }

//    @Override
//    public Result<List<RentalPackge>>  packageList(String carTypeId){
//        LambdaQueryWrapper<RentalPackge> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(RentalPackge::getCarTypeId,carTypeId);
//        List<RentalPackge> dataList = rentalPackgeMapper.selectList(queryWrapper);
//        return Result.OK(dataList);
//    }


//    @Override
//    public Result bind(AccountBindingCarReq bindingCarReq) {
//        //1、车辆是否已经绑定着有效套餐
//        RentalAccount account=baseMapper.selectById(bindingCarReq.getAccountId());
//        if (account.getCarId()!=null){
//            Result.error("已有绑定车辆");
//        }
//
//        //2、当前套餐是否有效
//        List<AccountRentalPackegeRsp> accountPackge = rentalAccountPackgeMapper.getRentalAccountPackge(bindingCarReq.getAccountId(), 2);
//
//
//        // 检查是否有有效套餐
//        if (accountPackge.size() != 0) {
//            // 获取车辆信息
//            RentalCar car = rentalEBikeMapper.queryIdBycode(bindingCarReq.getCarCode());
//
//            // 检查车辆是否已经被其他用户使用
//            QueryWrapper<RentalAccount> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("car_id", car.getId());
//            List<RentalAccount> existingAccounts = baseMapper.selectList(queryWrapper);
//            if (!existingAccounts.isEmpty()) {
//                return Result.error("车辆已被其他用户绑定");
//            }
//
//            // 绑定车辆
//            account.setCarId(car.getId());
//            baseMapper.updateById(account);
//            return Result.OK();
//        }
//        return Result.error("绑定失败,无可用套餐");
//    }

    @Override
    public RentalAccount queryAuthentication() {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalAccount payAccount = baseMapper.selectById(rentalAccount.getId());
        if (payAccount==null){
            throw new JeecgBootException("rentalpayaccount.service.user.not.register");
        }
        payAccount.setIdentityNumber(DesensitizedUtil.idCardNum(payAccount.getIdentityNumber(), 8, 6));
        payAccount.setPhone(DesensitizedUtil.mobilePhone(payAccount.getPhone()));
        return payAccount;
    }


//    @Override
//    public List<RentalCarType> lists() {
//        return rentalEBikeTypeMapper.lists();
//    }


//    @Override
//    @Transactional
//    public Result<Boolean> depositRefund(String accountPackageId) {
//        RentalAccountPackage rentalAccountPackage = rentalAccountPackageMapper.selectById(accountPackageId);
////        // 判断是否有使用中的车辆,用户只能租一辆车
////        if (null!= rentalPayAccount.getCarId()){
////            throw new JeecgBootException("还车才能发起押金退款");
////        }
//        if (rentalAccountPackage!=null){
//            if (rentalAccountPackage.getDepositStatus()==0){
//                // 状态提现中(修改押金状态)
//                RentalOrder orderBycar = rentalOrderMapper.lastOrder(
//                            new QueryWrapper<RentalOrder>().eq("account_package_id", accountPackageId)
////                                    .eq("car_id", carId)
//                                    .eq("order_type", 1)
//                                    .eq("order_status", 2)
//                            );
////                List<RentalOrder> orderBycar = rentalOrderMapper.getOrderByUseId(openId,1,2);
////                rentalPayAccount.setDepositType(3);
//                rentalAccountPackage.setDepositStatus(1);
//
//                RentalWithdrawalReview rwr=new RentalWithdrawalReview();
//
////                if (orderBycar.size()!=0){
//                    rwr.setPaymentNo(orderBycar.getOrderCode());
////                }
//                rwr.setAccountId(orderBycar.getAccountId());
////                rwr.setId(UuidUtil.getRandomUuid());
//                rwr.setAmountMoney(orderBycar.getDepositAmount());
////                rentalPayAccount.setAccountDeposit(new BigDecimal(0.00));
//                // todo 暂定用户创建时的运营商
////                rwr.setSysOrgCode(chargePayAccount.getSysOrgCode());
//                // 待审核中
//                rwr.setCarTypeId(orderBycar.getCarTypeId());
//                rwr.setWithdrawalStatus(1);
//                //rwr.setCreationTime(new Date());
//                rwr.setOrderNo(RandomUtil.getRandomCode());
//                rentalWithdrawalReviewMapper.insert(rwr);
//                rentalAccountPackageMapper.updateById(rentalAccountPackage);
////                baseMapper.updateById(rentalPayAccount);
//            }else {
//                throw new JeecgBootException("rentalpayaccount.service.deposit.not.refundable");
//            }
//        }
//        return Result.OK();
//    }

//    @Override
//    @Transactional
//    public Result<Boolean> refundDep(RentalAccountPackage rentalAccountPackage) throws Exception {
//        //RentalAccountPackage rentalAccountPackage = rentalAccountPackageMapper.selectById(accountPackageId);
//        if (rentalAccountPackage!=null){
//            if (rentalAccountPackage.getDepositStatus()==0 && rentalAccountPackage.getReturnTime() != null){
//                Duration duration = Duration.between(rentalAccountPackage.getStartTime(), rentalAccountPackage.getReturnTime());
//                long minutesElapsed = duration.toMinutes();
//
//                // 状态提现中(修改押金状态)
//                RentalOrder orderBycar = rentalOrderMapper.lastOrder(
//                        new QueryWrapper<RentalOrder>().eq("account_package_id", rentalAccountPackage.getId())
////                                    .eq("car_id", carId)
//                                .eq("order_type", 1)
//                                .eq("order_status", 2)
//                );
//                /*// 查询相关的租赁订单
//                LambdaQueryWrapper<RentalOrder> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(RentalOrder::getPackageConfId, rentalAccountPackage.getId());
//                queryWrapper.eq(RentalOrder::getOrderType, 1); // orderType 为 1
//                RentalOrder rentalOrder = rentalOrderMapper.selectOne(queryWrapper);*/
//                IWechatService wechatService = wechatServiceFactory.getWechatService(orderBycar.getSysOrgCode());
//
//
//                //生成
//                RefundOrderResp refundResultInfo= null;
//                //refundResultInfo = PaymentWx.refund(null,rwr.getOrderNo(), RandomUtil.getRandomCode(),"退款",null,rwr.getAmountMoney() ,totalMoney  );
//                RefundOrderReq refundOrderReq=new RefundOrderReq();
//                refundOrderReq.setTransactionId(null);
//                refundOrderReq.setOrderId(orderBycar.getOrderCode());
//                refundOrderReq.setRefundOrderId(RandomUtil.getRandomCode());
//                refundOrderReq.setReason("押金退款");
//                refundOrderReq.setNotifyUrl(null);
//                refundOrderReq.setRefundMoney(orderBycar.getDepositAmount());
//                refundOrderReq.setTotalMoney(orderBycar.getPayAmount());
//
//                refundResultInfo = wechatService.refund(refundOrderReq);
//                if ("PROCESSING".equals(refundResultInfo.getStatus())||"SUCCESS".equals(refundResultInfo.getStatus())) {
//                    rentalAccountPackage.setDepositStatus(1);
//                }
//                rentalAccountPackageMapper.updateById(rentalAccountPackage);
////                baseMapper.updateById(rentalPayAccount);
//            }else {
//                throw new JeecgBootException("rentalpayaccount.service.deposit.not.refundable");
//            }
//        }
//        return Result.OK();
//    }


//    @Override
//    @Transactional
//    public Result<Boolean> allRefund(RentalAccountPackage rentalAccountPackage) throws Exception {
//        //RentalAccountPackage rentalAccountPackage = rentalAccountPackageMapper.selectById(accountPackageId);
//        if (rentalAccountPackage!=null){
//            if (rentalAccountPackage.getDepositStatus()==0 && rentalAccountPackage.getReturnTime() != null){
//                Duration duration = Duration.between(rentalAccountPackage.getStartTime(), rentalAccountPackage.getReturnTime());
//                long minutesElapsed = duration.toMinutes();
//
//                if (minutesElapsed > 5) { // 假设超过5分钟就不能退款
//                    throw new JeecgBootException("rentalpayaccount.service.refund.timeout");
//                }
//
//                // 状态提现中(修改押金状态)
//                RentalOrder orderBycar = rentalOrderMapper.lastOrder(
//                        new QueryWrapper<RentalOrder>().eq("account_package_id", rentalAccountPackage.getId())
////                                    .eq("car_id", carId)
//                                .eq("order_type", 1)
//                                .eq("order_status", 2)
//                );
//                // 查询相关的租赁订单
//             /*   LambdaQueryWrapper<RentalOrder> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(RentalOrder::getPackageConfId, rentalAccountPackage.getId());
//                queryWrapper.eq(RentalOrder::getOrderType, 1); // orderType 为 1
//                RentalOrder rentalOrder = rentalOrderMapper.selectOne(queryWrapper);*/
//                IWechatService wechatService = wechatServiceFactory.getWechatService(orderBycar.getSysOrgCode());
//
//
//                //生成
//                RefundOrderResp refundResultInfo= null;
//                //refundResultInfo = PaymentWx.refund(null,rwr.getOrderNo(), RandomUtil.getRandomCode(),"退款",null,rwr.getAmountMoney() ,totalMoney  );
//                RefundOrderReq refundOrderReq=new RefundOrderReq();
//                refundOrderReq.setTransactionId(null);
//                refundOrderReq.setOrderId(orderBycar.getOrderCode());
//                refundOrderReq.setRefundOrderId(RandomUtil.getRandomCode());
//                refundOrderReq.setReason("退款");
//                refundOrderReq.setNotifyUrl(null);
//                refundOrderReq.setRefundMoney(orderBycar.getPayAmount());
//                refundOrderReq.setTotalMoney(orderBycar.getPayAmount());
//                refundResultInfo = wechatService.refund(refundOrderReq);
//                if ("PROCESSING".equals(refundResultInfo.getStatus())||"SUCCESS".equals(refundResultInfo.getStatus())) {
//                    rentalAccountPackage.setDepositStatus(1);
//                }
//                rentalAccountPackageMapper.updateById(rentalAccountPackage);
////                baseMapper.updateById(rentalPayAccount);
//            }else {
//                throw new JeecgBootException("rentalpayaccount.service.deposit.not.refundable");
//            }
//        }
//        return Result.OK();
//    }


    @Override
    public Result<Boolean> unsubscribePackage(String openId, String id) {
        RentalAccountPackage rentalAccountPackage=rentalAccountPackageMapper.selectById(id);
        if (rentalAccountPackage!=null){
            if (rentalAccountPackage.getAccountId().equals(openId)){
                // 设置套餐为退订状态
                rentalAccountPackageMapper.updateById(rentalAccountPackage);
            }else{
                return Result.OK(false);
            }
        }else{
            throw new JeecgBootException("rentalpayaccount.service.package.not.found");
        }
        return Result.OK(true);
    }


//    @Override
//    public  Result<Page<RentalWithdrawalReviewReq>> withdrawalList(String openId, int pageNum, int pageSize) {
//        LambdaQueryWrapper<RentalWithdrawalReviewReq> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(RentalWithdrawalReviewReq::getAccountId,openId);
//        Page<RentalWithdrawalReviewReq> page = new Page<>(pageNum, pageSize);
//        Page<RentalWithdrawalReviewReq> resultPage = rentalWithdrawalReviewMapper.selectDetailPage(page, queryWrapper );
//        Page<RentalWithdrawalReviewReq> pageResult = new Page<>();
//        pageResult.setRecords(resultPage.getRecords());
//        pageResult.setCurrent(resultPage.getCurrent());
//        pageResult.setSize(resultPage.getSize());
//        pageResult.setTotal(resultPage.getTotal());
//        return Result.OK(resultPage);
//    }

    @Override
    public RentalAccount initPassword(String accountId) {
        RentalAccount payAccount = baseMapper.selectById(accountId);
        payAccount = resetPassword(payAccount);
        baseMapper.updateById(payAccount);
        return payAccount;
    }

    @Override
    public RentalAccount initPayAccount(String openid) {
        RentalAccount rentalPayAccount = new RentalAccount();
        //TODO openId做主键
        rentalPayAccount.setWxOpenId(openid);
        rentalPayAccount.setAccountCode(RandomUtil.getRandomCode());
        rentalPayAccount = resetPassword(rentalPayAccount);
        baseMapper.insert(rentalPayAccount);
        return rentalPayAccount;
    }

    @Override
    public RentalAccount getAccountByCode(String code) {
        RentalAccount rentalPayAccount = baseMapper.selectOne(new QueryWrapper<RentalAccount>().eq("account_code", code).or().eq("email", code).or().eq("phone", code));
        if(ObjectUtil.isNotEmpty(rentalPayAccount)){
            RentalAccount rentalAccount = new RentalAccount();
            BeanUtil.copyProperties(rentalPayAccount, rentalAccount);
            return rentalAccount;
        }
        return null;
    }

    @Override
    public void addAccount(RentalAccount rentalPayAccount) {
        RentalAccount entity = new RentalAccount();
        entity.setAccountCode(RandomUtil.getRandomCode());
        entity.setPhone(rentalPayAccount.getPhone());
        entity.setEmail(rentalPayAccount.getEmail());
//        entity.setAccountBalance(new BigDecimal(0.00));
        entity = resetPassword(entity);
        baseMapper.insert(entity);
    }

    @Override
    public RentalAccount resetPassword(RentalAccount rentalPayAccount) {
        String password = "123456", salt = oConvertUtils.randomGen(8);
        String passwordEncode = PasswordUtil.encrypt(rentalPayAccount.getAccountCode(), password, salt);
        rentalPayAccount.setSalt(salt);
        rentalPayAccount.setPassword(passwordEncode);
        return rentalPayAccount;
    }

    @Override
    public RentalAccount getCurrentUserAccount() {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        return baseMapper.selectById(rentalAccount.getId());
    }

    @Override
    public LoginRentalAccount getEncodeRentalAccount(String account) {
        if(oConvertUtils.isEmpty(account)) {
            return null;
        }
        String tenantId = TenantContext.getTenant();
        LoginRentalAccount rentalAccount = new LoginRentalAccount();
        RentalAccount rentalPayAccount = baseMapper.findOneNoTenant(new QueryWrapper<RentalAccount>()
                        .eq(oConvertUtils.isNotEmpty(tenantId), "tenant_id", tenantId)
                .and(wq -> wq.eq("account_code", account).or().eq("email", account).or().eq("phone", account)));
        if(oConvertUtils.isEmpty(rentalPayAccount)) {
            throw new JeecgBootException("rentalpayaccount.auth.user.not.found");
        }
        BeanUtil.copyProperties(rentalPayAccount, rentalAccount);
        Cache cache = cacheManager.getCache(RentalConstant.RENTAL_ACCOUNTS_CACHE);
        cache.put(tenantId + ":" + rentalAccount.getAccountCode(), rentalAccount);
        return rentalAccount;
    }

    @Override
    public LoginRentalAccount getEncodeRentalAccountByOpenId(String openid) {
        if(oConvertUtils.isEmpty(openid)) {
            return null;
        }
        String tenantId = TenantContext.getTenant();
        LoginRentalAccount rentalAccount = new LoginRentalAccount();
        RentalAccount rentalPayAccount = baseMapper.findOneNoTenant(new QueryWrapper<RentalAccount>()
                .eq(oConvertUtils.isNotEmpty(tenantId), "tenant_id", tenantId)
                .eq("wx_open_id", openid));
        if(rentalPayAccount == null) {
            rentalPayAccount = this.initPayAccount(openid);
        }
        if(ObjectUtil.isEmpty(rentalPayAccount.getPassword()) || ObjectUtil.isEmpty(rentalPayAccount.getSalt())){
            rentalPayAccount = this.initPassword(openid);
        }
        BeanUtil.copyProperties(rentalPayAccount, rentalAccount);
        Cache cache = cacheManager.getCache(RentalConstant.RENTAL_ACCOUNTS_CACHE);
        cache.put(tenantId + ":" + rentalAccount.getAccountCode(), rentalAccount);
        return rentalAccount;
    }

    @Override
    public Boolean bindPhone(String phone) {
        LoginRentalAccount account = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalAccount rentalAccount = baseMapper.selectById(account.getId());
        rentalAccount.setPhone(phone);
        return baseMapper.updateById(rentalAccount) > 0;
    }

    @Override
    public Boolean bindCid(Long accountId, String cid, String clientCode, String clientPlatform) {
        if(ObjectUtil.isEmpty(accountId) || StrUtil.isBlank(cid)){
            return false;
        }

        RentalAccount rentalAccount = baseMapper.selectById(accountId);
        if(!cid.equals(rentalAccount.getCid())){
            rentalAccount.setCid(cid);
            rentalAccount.setClientCode(clientCode);
            rentalAccount.setClientPlatform(clientPlatform);
            baseMapper.updateById(rentalAccount);
        }
        return true;
    }

    @Override
    public LoginRentalAccount getLoginRentalAccountByWxOpenId(String openid) {
        if (oConvertUtils.isEmpty(openid)) {
            return null;
        }
        LoginRentalAccount rentalAccount = this.getEncodeRentalAccountByOpenId(openid);
        //相同类中方法间调用时脱敏解密 Aop会失效，获取用户信息太重要，此处采用原生解密方法，不采用@SensitiveDecodeAble注解方式
        try {
            SensitiveInfoUtil.handlerObject(rentalAccount, false);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return rentalAccount;
    }

    @Override
    public LoginRentalAccount getLoginRentalAccountByAccount(String account) {
        if (oConvertUtils.isEmpty(account)) {
            return null;
        }
        LoginRentalAccount rentalAccount = this.getEncodeRentalAccount(account);
        //相同类中方法间调用时脱敏解密 Aop会失效，获取用户信息太重要，此处采用原生解密方法，不采用@SensitiveDecodeAble注解方式
        try {
            SensitiveInfoUtil.handlerObject(rentalAccount, false);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return rentalAccount;
    }

    @Override
    public RentalAccount findOneNoTenant(Wrapper<RentalAccount> wrapper) {
        return baseMapper.findOneNoTenant(wrapper);
    }


}
